<template>
  <div class="admin-container">
    <div class="table-btn">
      <el-button @click="dialogVisible = true">新增台账</el-button>
    </div>
    <div class="table-container">
      <el-table :data="pointsTableList" height="750" border style="width: 100%">
        <el-table-column prop="id" label="序号Id" width="80" fixed />
        <el-table-column prop="pointName" label="点位名称" width="100" />
        <el-table-column prop="leadDept" label="属地" />
        <el-table-column prop="location" label="隐患地点" width="100" />
        <el-table-column prop="typeName" label="隐患类别" width="100" />
        <el-table-column prop="reason" label="产生隐患原因" width="120" />
        <el-table-column prop="basicInfo" label="基本情况" width="250" />
        <el-table-column prop="responsibleDept" label="牵头单位" width="100" />
        <el-table-column prop="address" label="配合单位" width="100" />
        <el-table-column prop="treatMeasure" label="应急措施" width="240" />
        <el-table-column prop="preProgress" label="前置力量" width="240" />
        <el-table-column prop="dutyOfficer" label="防汛责任人" width="100" />
        <el-table-column prop="telephone" label="联系电话" width="120" />
        <el-table-column prop="address" label="现场图片">
          <template #default="{ row }">
            <div>
              <img
                v-show="row.images && row.images.length > 0"
                v-for="url in row.images?.split(',')"
                :src="BASEURL + url"
                width="100"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="editPoint(row)">
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="delPoint(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-drawer
    v-model="dialogVisible"
    :title="pointForm.id ? '编辑隐患点位' : '新增'"
    :size="500"
    direction="rtl"
    @close="closeDialog"
  >
    <el-form :model="pointForm" label-width="100px" ref="formRef">
      <el-form-item label="点位名称" prop="pointName">
        <el-input v-model="pointForm.pointName" />
      </el-form-item>
      <el-form-item label="隐患类别" prop="typeId">
        <el-select
          v-model="pointForm.typeId"
          @change="typeChange"
          placeholder="请选择隐患类别"
        >
          <el-option-group
            v-for="group in typeTableList"
            :key="group.id"
            :label="group.name"
          >
            <el-option
              v-for="item in group.children"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item label="基本情况" prop="basicInfo">
        <el-input v-model="pointForm.basicInfo" />
      </el-form-item>
      <el-form-item label="防汛负责人" prop="dutyOfficer">
        <el-input v-model="pointForm.dutyOfficer" />
      </el-form-item>
      <el-form-item label="消除措施" prop="eliminateMeasure">
        <el-input v-model="pointForm.eliminateMeasure" />
      </el-form-item>
      <el-form-item label="牵头单位" prop="leadDept">
        <el-input v-model="pointForm.leadDept" />
      </el-form-item>
      <el-form-item label="隐患地点" prop="location">
        <el-input v-model="pointForm.location" />
      </el-form-item>
      <el-form-item label="隐患地点" prop="location">
        <el-input v-model="pointForm.location" />
      </el-form-item>
      <el-form-item label="前置力量" prop="preProgress">
        <el-input v-model="pointForm.preProgress" />
      </el-form-item>
      <el-form-item label="产生隐患原因" prop="reason">
        <el-input v-model="pointForm.reason" />
      </el-form-item>
      <el-form-item label="责任单位" prop="responsibleDept">
        <el-input v-model="pointForm.responsibleDept" />
      </el-form-item>
      <el-form-item label="联系电话" prop="telephone">
        <el-input v-model="pointForm.telephone" />
      </el-form-item>
      <el-form-item label="属地" prop="town">
        <el-input v-model="pointForm.town" />
      </el-form-item>
      <el-form-item label="应急措施" prop="treatMeasure">
        <el-input v-model="pointForm.treatMeasure" />
      </el-form-item>
      <el-form-item label="现场照片" prop="images">
        <el-upload
          :file-list="fileList"
          action="#"
          list-type="picture-card"
          :http-request="uploadHandler"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createPoint"> 确认 </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getPointsAllAPI,
  getTypeAllAPI,
  createPointAPI,
  delPointAPI,
  updatePointAPI,
  uploadImgAPI,
} from '@/apis/index'
import { BASEURL } from '@/apis/http'
import { arr2tree } from '@/utils/arr2tree'
// 获取points
const pointsTableList = ref([])
const getPointsAll = async () => {
  const res = await getPointsAllAPI()
  pointsTableList.value = res.data.data
}
getPointsAll()

// 获取渲染数据
const typeTableList = ref([])
const getTypesAll = async () => {
  const res = await getTypeAllAPI()
  typeTableList.value = arr2tree(res.data.data)
}
getTypesAll()

const typeChange = (typeId) => {
  const typeObj = typeTableList.value.find((item) => item.id === typeId)
  pointForm.value.typeName = typeObj.name
}

// 新增point
const formRef = ref(null)
const pointForm = ref({
  basicInfo: '',
  cooperateDept: '',
  dutyOfficer: '',
  eliminateMeasure: '',
  images: '',
  leadDept: '',
  location: '',
  pointName: '',
  preProgress: '',
  reason: '',
  responsibleDept: '',
  telephone: '',
  town: '',
  treatMeasure: '',
  typeId: '',
  typeName: '',
})

const createPoint = async () => {
  if (pointForm.value.id) {
    // 更新
    await updatePointAPI({
      ...pointForm.value,
      images: fileList.value
        .map((file) => {
          return file.reqUrl ? file.reqUrl : file.url
        })
        .join(','),
    })
  } else {
    // 新增
    await createPointAPI({
      ...pointForm.value,
      images: fileList.value.map((file) => file.url).join(','),
    })
  }
  // 更新列表
  getPointsAll()
  ElMessage({
    message: `${pointForm.value.id ? '更新' : '新增'}成功`,
    type: 'success',
  })
  dialogVisible.value = false
}

// 编辑
const editPoint = (row) => {
  pointForm.value = JSON.parse(JSON.stringify(row))
  if (pointForm.value.images === '' || pointForm.value.images == null) {
    fileList.value = []
  } else {
    fileList.value = pointForm.value.images?.split(',').map((url) => {
      return {
        url: BASEURL + url,
        reqUrl: url,
      }
    })
  }
  dialogVisible.value = true
}

// 删除
const delPoint = (id) => {
  ElMessageBox.confirm('确认删除吗?', 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await delPointAPI(id)
    // 更新列表
    getPointsAll()
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  })
}

// 创建
const dialogVisible = ref(false)

const closeDialog = () => {
  formRef.value.resetFields()
  pointForm.value = {
    basicInfo: '',
    cooperateDept: '',
    dutyOfficer: '',
    eliminateMeasure: '',
    images: '',
    leadDept: '',
    location: '',
    pointName: '',
    preProgress: '',
    reason: '',
    responsibleDept: '',
    telephone: '',
    town: '',
    treatMeasure: '',
    typeId: '',
    typeName: '',
  }
  fileList.value = []
}

// 上传图片
const fileList = ref([])
const uploadHandler = async (resFile) => {
  const fd = new FormData()
  fd.append('file', resFile.file)
  const res = await uploadImgAPI(fd)
  fileList.value.push({
    uid: resFile.file.uid,
    url: res.data.data,
  })
}
</script>

<style lang="css" scoped>
.admin-container {
  margin: 0 auto;
}
.table-title {
  text-align: center;
  font-size: 22px;
  color: rgb(0, 0, 0, 0.7);
}
.table-btn {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}
</style>
